/**
 * 替换所有的fot循环为fotEach
 */

const babel = require('@babel/core');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;

// 要转换的代码
const code = `
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}
`;

// 解析代码为 AST
const ast = parser.parse(code);

// 定义 visitor 对象
const visitor = {
    ForStatement(path) {
        const { init, test, update, body } = path.node;
        const arrayName = init.declarations[0].init.name; // 假设数组名在初始化中

        // 创建 forEach 调用
        const forEachCall = {
            type: 'CallExpression',
            callee: {
                type: 'MemberExpression',
                object: {
                    type: 'Identifier',
                    name: arrayName
                },
                property: {
                    type: 'Identifier',
                    name: 'forEach'
                }
            },
            arguments: [
                {
                    type: 'ArrowFunctionExpression',
                    params: [init.declarations[0].id],
                    body: body
                }
            ]
        };

        path.replaceWith(forEachCall);
    }
};

// 遍历 AST
traverse(ast, visitor);

// 将修改后的 AST 转换回代码
const { code: transformedCode } = generate(ast);

// 输出转换后的代码
console.log(transformedCode);
// 输出
// const numbers = [1, 2, 3, 4, 5];
// numbers.forEach((i) => {
//     console.log(i);
// });